package n1007;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.StringTokenizer;

public class Main {

	static int s[]=new int[4];
	
	static int getIndex(char c)
	{
		int result=0;
		switch(c)
		{
		case 'A':result=0;break;
		case 'C':result=1;break;
		case 'G':result=2;break;
		case 'T':result=3;break;
		}
		return result;
	}
	
	
	static int getSortedN(String str)
	{
		Arrays.fill(s, 0);
		
		int sorted=0;
		
		for(int i=0;i<str.length();i++)
		{
			int k=getIndex(str.charAt(i));
			s[k]++;
			for(int j=k+1;j<4;j++)
			{
				sorted+=s[j];
			}
		}
		return sorted;
	}
	
	static class Node{
		String line;
		int sorted;
		int index;
	}
	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {

		List<Node> list=new ArrayList<Node>();
		BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer(bf.readLine());
		int n=Integer.parseInt(st.nextToken());
		int m=Integer.parseInt(st.nextToken());
		for(int i=0;i<m;i++)
		{
			Node node=new Node();
			node.index=i;
			node.line=bf.readLine();
			node.sorted=getSortedN(node.line);
			list.add(node);
		}
		
		Collections.sort(list, new Comparator<Node>(){
			public int compare(Node o1, Node o2) {
				if(o1.sorted==o2.sorted)
				{
					return o1.index-o2.index;
				}
				return o1.sorted-o2.sorted;
			}
		});
		
		for(Node node:list)
		{
			System.out.println(node.line);
		}
		
	}

}
